from zipfile import ZipFile
import os
import shutil
import tqdm
from concurrent.futures import ThreadPoolExecutor

class ZipFiles():
    def __init__(self):
        self.file_count = 1
        self.dir_count = 1

    def unzipFiles(self,zip_list):
        file_name = os.path.basename(zip_list)
        folder_name = os.path.splitext(file_name)[0]
        os.mkdir(f'./data/{folder_name}')
        ZipFile(zip_list,'r').extractall(f'./data/{folder_name}')
        files_name = f'./data/{folder_name}'
        self.read_all_files(files_name,folder_name)

    def read_all_files(self,files_Path,folder_name):
        qwd_list = os.listdir(files_Path)
        for i in tqdm.tqdm(qwd_list):
            directoryName = files_Path+'/'+i
            if os.path.isdir(directoryName):  #file_Path是二级目录
                self.read_all_files(directoryName,folder_name)
            else:
                fileExtension = os.path.splitext(i)
                if fileExtension[1] == '.jpg' or fileExtension[1] == '.png':
                    img_Path = directoryName
                    self.subcontract(img_Path,folder_name)

    def subcontract(self,img_Path, folder_name):
        package_Path = f'./data/{folder_name}_sub'
        if not os.path.exists(package_Path):
            os.mkdir(package_Path)
        newnames = package_Path+f'/xxxx_{folder_name[-2:]}_{str(self.dir_count).zfill(4)}_sub/xxxx_{folder_name[-2:]}_{str(self.file_count).zfill(6)}.jpg'
        if self.file_count%20!=0:
            if not os.path.exists(package_Path+f'/xxxx_{folder_name[-2:]}_{str(self.dir_count).zfill(4)}_sub'):
                os.mkdir(package_Path + f'/xxxx_{folder_name[-2:]}_{str(self.dir_count).zfill(4)}_sub')
            shutil.copyfile(img_Path, newnames)
            self.file_count += 1
        else:
            shutil.copyfile(img_Path, newnames)

            self.dir_count += 1
            self.file_count += 1

        with open(f'{package_Path}/pathDetails.txt','a') as f:
            f.write(img_Path+'---'+newnames+'\n')

if __name__ == '__main__':
    zip_list = ['./xxx.zip','./yyyy.zip']
    if not os.path.exists('./data'):
        os.mkdir('./data')
    with ThreadPoolExecutor(20) as t:
        for i in zip_list:
            root = ZipFiles()
            t.submit(root.unzipFiles(i))

